<?php
/**
 * Created by PhpStorm.
 * User: xmy2
 * Date: 18-9-9
 * Time: 下午8:36
 */

namespace vola;


class Socket
{
    private $address, $port;
    protected static $end = false;

    public function __construct($address = '0.0.0.0', $port = '7999')
    {
        $this->address = $address;
        $this->port = $port;
    }

    public function run() {
        $this->server = socket_create($this->address, '', '');

        while (true) {
            $hook = Container::get('hook');
            $hook->do_action('socket');

            if (self::$end) {
                break;
            }
        }
    }

    public static function changeStatus() {
        self::$end = true;
    }

    /**
     * 握手处理
     * @param $newClient socket
     * @return int 接收到的信息
     */
    public function handshaking($newClient, $line){

        $headers = array();
        $lines = preg_split("/\r\n/", $line);
        foreach($lines as $line)
        {
            $line = chop($line);
            if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
            {
                $headers[$matches[1]] = $matches[2];
            }
        }
        $secKey = $headers['Sec-WebSocket-Key'];
        $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
        $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
            "Upgrade: websocket\r\n" .
            "Connection: Upgrade\r\n" .
            "WebSocket-Origin: $this->address\r\n" .
            "WebSocket-Location: ws://$this->address:$this->port/websocket/websocket\r\n".
            "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
        return socket_write($newClient, $upgrade, strlen($upgrade));
    }
}